package com.xyongfeng.foodManagement.controller;


import com.xyongfeng.foodManagement.common.BaseResponse;
import com.xyongfeng.foodManagement.common.ErrorCode;
import com.xyongfeng.foodManagement.common.ResultUtils;
import com.xyongfeng.foodManagement.domain.FoodCategoryInfo;
import com.xyongfeng.foodManagement.domain.FoodCategoryView;
import com.xyongfeng.foodManagement.domain.group.AddGroup;
import com.xyongfeng.foodManagement.domain.group.EditGroup;
import com.xyongfeng.foodManagement.domain.group.NormalGroup;
import com.xyongfeng.foodManagement.service.FoodCategoryInfoService;
import com.xyongfeng.foodManagement.service.FoodCategoryViewService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 控制食品类别的接口
 *
 * @author xyongfeng
 */
@RestController
@RequestMapping("/foodCategory")
@Slf4j

public class FoodCategoryController {

    @Autowired
    private FoodCategoryInfoService foodCategoryInfoService;
    @Autowired
    private FoodCategoryViewService foodCategoryViewService;


    @GetMapping
    public BaseResponse<List<FoodCategoryInfo>> selectAll() {
        return ResultUtils.success(foodCategoryInfoService.list());
    }

    @RequiresPermissions("foodCategory")
    @PostMapping
    public BaseResponse<FoodCategoryInfo> insert(@RequestBody @Validated({AddGroup.class, NormalGroup.class})
                                                     FoodCategoryInfo foodCategoryInfo) {

        foodCategoryInfoService.save(foodCategoryInfo);

        return ResultUtils.success(foodCategoryInfo);
    }

    @RequiresPermissions("foodCategory")
    @DeleteMapping("/{id}")
    public BaseResponse<FoodCategoryInfo> deleteById(@PathVariable Long id) {

        FoodCategoryInfo foodCategoryInfoById = foodCategoryInfoService.getById(id);

        boolean b = foodCategoryInfoService.removeById(id);
        if (!b) return ResultUtils.error(ErrorCode.OPERATION_ERROR, "删除失败");
        return ResultUtils.success(foodCategoryInfoById);
    }
    @RequiresPermissions("foodCategory")
    @PutMapping
    public BaseResponse<FoodCategoryInfo> updateById(@RequestBody @Validated({EditGroup.class, NormalGroup.class}) FoodCategoryInfo foodCategoryInfo) {

        boolean foodCategoryInfoById = foodCategoryInfoService.updateById(foodCategoryInfo);
        if (!foodCategoryInfoById) return ResultUtils.error(ErrorCode.OPERATION_ERROR.getCode(), "修改失败");
        foodCategoryInfo = foodCategoryInfoService.getById(foodCategoryInfo.getCategoryId());

        return ResultUtils.success(foodCategoryInfo);
    }

    @GetMapping("/view")
    public BaseResponse<List<FoodCategoryView>> selectView() {
        return ResultUtils.success(foodCategoryViewService.list());
    }

}
